<style lang="css">
#origin-bom-tree {
  margin: 5px 5px;
  border-style: solid;
  border-radius: 10px;
  border-width: 1.5px;
  padding: 5px;
}

#technique-bom-tree {
  margin: 5px 5px;
  border-style: solid;
  border-radius: 10px;
  border-width: 1.5px;
  padding: 5px;
}

.container {
  display: flex;
  width: 100%;
  align-items: center;
}

.left {
  margin-right: auto;
}

.middle {
}

.right {
  margin-left: auto;
}
</style>

<template>
  <div style="text-align: center">
    <!-- <span v-if="status">Loading...</span> -->
    <!-- <div v-else> -->
    <div class="container">
      <div class="left">
        <span v-if="status">Loading...</span>
        <div v-else>
          <div v-if="!sessionId">
            <el-icon><CloseBold /></el-icon><span style="color: red">disconnected</span>
          </div>
          <div v-else>
            <el-icon><Link /></el-icon><span style="color: greenyellow">connected</span>
          </div>
        </div>
      </div>
      <div class="middle">
        <h4>工艺BOM编辑器</h4>
      </div>
      <div class="right">
        <ElButton @click="redo"
          ><el-icon><CirclePlus /></el-icon>连接</ElButton
        >
        <ElButton @click="displayFileSelectDialog"
          ><el-icon><Files /></el-icon>导入</ElButton
        >
        <ElButton @click="outputState"
          ><el-icon><Share /></el-icon>导出</ElButton
        ><ElButton @click="outputTest"
          ><el-icon><Share /></el-icon>导出工艺bom</ElButton
        >
      </div>
      <!-- </div> -->
    </div>
  </div>
  <input
    ref="fileInputElement"
    type="file"
    class="hidden"
    @change="handleFileInput"
    accept=".bom"
  />
  <hr />

  <el-row :gutter="20">
    <el-col :span="12">
      <div id="origin-bom-tree">
        <ElScrollbar height="450px">
          <OriginBomTree :data-source="bom" :defaultExpandAll="true" ref="treeOut" />
        </ElScrollbar>
      </div>
    </el-col>
    <el-col :span="12">
      <div id="technique-bom-tree">
        <ElScrollbar height="450px">
          <TechniqueBomTree
            :product-name="productName"
            ref="treeIn"
            @unhide="(id) => dealUnHide(id)"
            @hide="(id) => dealHide(id)"
            @clear="clearTemp"
          />
        </ElScrollbar>
      </div>
    </el-col>
  </el-row>
</template>

<script setup lang="ts">
import { onMounted, ref, onBeforeUnmount } from 'vue'
import { connectCreoson, getBom } from '@/utils/creoson'
import OriginBomTree from './components/OriginBomTree.vue'
import TechniqueBomTree from './components/TechniqueBomTree.vue'
import { Tree } from './types/tree-type'
import { ElButton, ElMessage, ElScrollbar } from 'element-plus'
import { exportBomImpl } from '@/utils/export-utils'
import { storage } from '@/utils/storage'

const sessionId = ref('')
const status = ref(true)
let bom = ref<Tree[]>([])
const productName = ref('')

//导出文件
const outputState = () => {
  const dataPack = {
    inData: treeIn.value?.handInItsData(),
    outData: bom.value,
    backendData: treeIn.value?.handInBackendData(),
  }
  exportBomImpl(JSON.stringify(dataPack), productName.value + '装配工艺')
}

//加载文件
const fileInputElement = ref(null)
const fileInput = ref(null)

//处理加载函数
const handleFileInput = (e) => {
  const file = e.target.files[0]
  if (!file) {
    return
  }

  const reader = new FileReader()

  reader.onload = (event) => {
    fileInput.value = event.target?.result

    if (fileInput.value != null) {
      const { inData, outData } = JSON.parse(fileInput.value)
      bom.value = outData
      treeIn.value?.recieveInputData(inData)
    }
  }

  reader.onerror = () => {
    console.log('文件读取失败')
    ElMessage.warning('文件读取失败，请重试')
  }

  reader.readAsText(file, 'utf-8')
}

// 正确类型：OriginBomTree 组件的实例类型
const treeOut = ref<InstanceType<typeof OriginBomTree>>()
const treeIn = ref<InstanceType<typeof TechniqueBomTree>>()

// 在加载完bom后给工艺bom绑定产品名
const setProductName = () => {
  const fileName = bom.value[0].file
  productName.value = fileName.slice(0, fileName.lastIndexOf('.'))
}

const dealHide = (id: number) => {
  // console.log('id:', id)
  treeOut.value?.hidePrtById(id, true)
}

const dealUnHide = (id: number) => {
  // console.log('id:', id)
  treeOut.value?.hidePrtById(id, false)
}

const clearTemp = () => {
  treeOut.value?.clearTemp()
}

const redo = () => {
  initializeData()
  treeIn.value?.recieveInputData({
    treeValue: [],
    inputValue: '',
  })
}

const initializeData = async () => {
  try {
    testConnection()
    const bomResult = await getBom(sessionId.value)
    bom.value = [bomResult]
    setProductName()
  } catch (error) {
    // console.log(error)
    console.error('处理连接时出错:', error)
  } finally {
  }
}

const testConnection = async () => {
  status.value = true
  const repId = await connectCreoson()
  sessionId.value = repId
  status.value = false
}

const displayFileSelectDialog = () => {
  fileInputElement.value.click()
}

onBeforeUnmount(() => {
  storage.set('originTreeValue', bom.value)
})

// window.addEventListener('beforeunload', () => {
//   console.log('beforeunload')
//   storage.set('originTreeValue', bom.value)
// })

onMounted(() => {
  testConnection()
  const originTreeValue = storage.get('originTreeValue')
  bom.value = originTreeValue
})

const outputTest = () => {
  exportBomImpl(treeIn.value?.handInTechniqueBomPrtCount(), productName.value + '工艺bom')
}
</script>

<style lang="css">
.hidden {
  display: none;
}
</style>
